package com.jykj.hqh;
import static anet.channel.util.Utils.context;

import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.graphics.Color;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.coordinatorlayout.widget.CoordinatorLayout;

import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import android.app.ActivityManager;
import android.annotation.TargetApi;
import io.flutter.embedding.android.FlutterActivity;
import android.graphics.drawable.Icon;
import java.io.InputStream;
import java.io.IOException;
import android.view.View;

import com.alibaba.sdk.android.push.HonorRegister;
import com.alibaba.sdk.android.push.huawei.HuaWeiRegister;
import com.alibaba.sdk.android.push.register.MiPushRegister;
import com.alibaba.sdk.android.push.register.VivoRegister;
import com.alibaba.sdk.android.push.register.OppoRegister;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.sdk.xmwebviewsdk.interf.HttpResponseCallBack;
import com.sdk.xmwebviewsdk.ui.XMSimpleWebViewActivity;
import com.sdk.xmwebviewsdk.utils.CommonUtils;
import com.sdk.xmwebviewsdk.view.XMWebView;
import com.umeng.analytics.MobclickAgent;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.commonsdk.utils.UMUtils;
import com.umeng.umverify.UMResultCode;
import com.umeng.umverify.UMVerifyHelper;
import com.umeng.umverify.listener.UMTokenResultListener;
import com.umeng.umverify.listener.UMPreLoginResultListener;
import com.umeng.umverify.listener.UMAuthUIControlClickListener;
import com.umeng.umverify.model.UMTokenRet;
import com.umeng.umverify.view.UMAuthUIConfig;
import java.util.HashMap;
import org.json.JSONException;
import org.json.JSONObject;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.Result;
// import com.alibaba.sdk.android.push.AndroidPopupActivity;
import java.util.Iterator;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Map;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import org.yaml.snakeyaml.Yaml;
import io.flutter.view.FlutterMain;
import android.content.res.AssetManager;
import android.content.Context;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.WindowManager;

import java.io.InputStream;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.json.JSONException;
import org.json.JSONObject;
import com.alibaba.sdk.android.push.CloudPushService;
import com.alibaba.sdk.android.push.CommonCallback;
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory;

public class MainActivity extends FlutterActivity {
    private static MainActivity instance;
    private static final String CHANNEL = "payment_channel";
    private static final String APP_METHOD_CHANNEL = "hqh_app_method_utils";
    MethodChannel flutterMethodChannel;
    private static final String TAG = "MainActivity";
    private boolean sdkAvailable = false;

    private static final String kSharedPreferencesName = "FlutterSharedPreferences";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        instance = this;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().setStatusBarColor(0);
        }

        AndroidBug5497Workaround.assistActivity(this);
    }

    public static MainActivity getInstance() {
        return instance;
    }

    @Override
    public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
        super.configureFlutterEngine(flutterEngine);
        flutterMethodChannel = new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(),
        APP_METHOD_CHANNEL);
                
        flutterMethodChannel.setMethodCallHandler(new MethodChannel.MethodCallHandler() {
            @Override
            public void onMethodCall(@NonNull MethodCall call, @NonNull MethodChannel.Result result) {
                String method = call.method;
                if (method.equals("getAndroidChannel")) {
                    String channel = getChannel(getApplicationContext());
                    result.success(channel);
                } else {
                    result.notImplemented();
                }
            }
        });

        new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), APP_METHOD_CHANNEL)
                .setMethodCallHandler((call, result) -> {
                    //友盟初始化
                    if (call.method.equals("umeng_register")) {
                        //获取参数
                        String appKey = call.argument("appkey");
                        String channel = call.argument("channel");
                        System.out.println("umeng_register appKey:" + appKey + " channel:" + channel);
                        UMConfigure.init(getApplicationContext(), appKey, channel, UMConfigure.DEVICE_TYPE_PHONE, "");
                        UMConfigure.setLogEnabled(true);
                    }
                    else if (call.method.equals("open_customer_service")) {
                        //打开客服
                        openCustomerService();
                    }
                    else {
                        result.notImplemented();
                    }
                });
    }

    public void openCustomerService() {
        CommonUtils.initCloudUrl(0, "N000000050920", "d6b65315-c59a-425c-b22f-4976b79636c7", null, new HttpResponseCallBack<String>() {
            @Override
            public void onSuccess(String s) {
                Log.i(TAG, "openCustomerService onSuccess: " + s);
                CommonUtils.mHandler.post(new Runnable() {
                    public void run() {
                        Intent intent = new Intent(MainActivity.this, CustomerWebViewActivity.class);
                        intent.putExtra("url", s);
                        startActivity(intent);
                        // 原来想用下面的方式实现，可以显示，但有软键盘覆盖输入框的问题
                        // bottomSheetDialog = new BottomSheetDialog(MainActivity.this);
                        // View bottomWebView = getLayoutInflater().inflate(R.layout.activity_customer_webview, null);
                        // XMWebView webView = bottomWebView.findViewById(R.id.webView);
                        // webView.loadUrl(s);
                        // bottomSheetDialog.setContentView(bottomWebView);
                        
                        // if (bottomSheetDialog.getWindow() != null) {
                        //     bottomSheetDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
                        //     // bottomSheetDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
                        // }
                        // bottomWebView.post(new Runnable() {
                        //     @Override
                        //     public void run() {
                        //         ViewGroup parent = (ViewGroup) bottomWebView.getParent();
                        //         BottomSheetBehavior<View> behavior = BottomSheetBehavior.from(parent);
                        //         behavior.setPeekHeight(bottomWebView.getHeight());
                        //         behavior.setHideable(false);
                        //         parent.setBackgroundResource(android.R.color.transparent);
                        //     }
                        // });
                        // bottomSheetDialog.show();
                    }
                });
//                startActivity((new Intent(context, CustomerWebView.class)).putExtra("url", s));
            }
            @Override
            public void onFailUre(String s) {
                Log.i(TAG, "openCustomerService onFailUre: " + s);
            }
        });
    }

    private String getChannel(Context context) {
        Bundle metaData = null;
        String apiKey = null;
        if (context == null) {
            return null;
        }
        try {
            ApplicationInfo ai = context.getPackageManager()
                    .getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
            if (null != ai) {
                metaData = ai.metaData;
            }
            if (null != metaData) {
                apiKey = metaData.getString("channel");
            }
        } catch (PackageManager.NameNotFoundException e) {
        }
        return apiKey;

    }

    private ActivityManager.TaskDescription setTaskDescriptionBeforeP() {
        Bitmap bitmapIcon = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
        return new ActivityManager.TaskDescription("红球会", bitmapIcon, Color.RED);
    }

    @TargetApi(Build.VERSION_CODES.P)
    private ActivityManager.TaskDescription setTaskDescriptionP() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            Bitmap bitmapIcon = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
            return new ActivityManager.TaskDescription("红球会", bitmapIcon, Color.RED);
        } else {
            return setTaskDescriptionBeforeP();
        }
    }
}
